import 'package:common_utils/common_utils.dart';
import 'package:fate_blind_box/utils/assets.dart';
import 'package:flutter/material.dart';

import '../../network/Api.dart';
import '../../theme/theme_color.dart';
import '../../widget/icon_text.dart';

//积分页面
class MyPointsUi extends StatelessWidget {
  const MyPointsUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _MyPointsWidget();
  }
}

class _MyPointsWidget extends StatefulWidget {
  const _MyPointsWidget({Key? key}) : super(key: key);

  @override
  State<_MyPointsWidget> createState() => _MyPointsWidgetState();
}

class _MyPointsWidgetState extends State<_MyPointsWidget> {
  // late double _screenWidth;
  // late double _screenHeight;
  final _listData = [];
  String str = "1234";
  int _page = 1;
  bool isLoading = false;
  Map _map = {};
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    str = "123";
    _getPointList(_page);
    _gettotalIncome();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });
  }

  _gettotalIncome() async {
    final res = await Api.getInstance().totalIntergalInfo();
    final data = res['data'];

    if (res['code'] == 0 && res['data'] != null) {
      _map = data;
    }
  }

  /// 下拉刷新方法,为list重新赋值
  Future<void> _onRefresh() async {
    await Future.delayed(const Duration(seconds: 3), () {});
  }

  /// 上拉加载更多
  Future _getMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      await Future.delayed(const Duration(seconds: 1), () {});
    }
  }

  _getPointList(int page) async {
    final res = await Api.getInstance().IntergalList(_page, 10);
    final data = res['data']['listsVOPageInfo']['list'];

    if (data != null) {
      List list = data;
      if (list.isNotEmpty) {
        _listData.clear();
        setState(() {
          _listData.addAll(list);
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    // _screenWidth = size.width;
    // _screenHeight = size.height;
    return Scaffold(
      appBar: getCommonAppBar("我的积分", color: Colors.black, fontsize: 16.0),
      body: str.isNotEmpty
          ? Container(
              margin: const EdgeInsets.only(top: 19, left: 14, right: 14),
              child: Stack(
                children: [
                  // Image.asset('images/ic_point.png'),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                          child: NestedScrollView(
                              headerSliverBuilder: (ctx, scrolled) {
                                return [_buildHeadInfo()];
                              },
                              body: Column(
                                children: [
                                  // _buildFilter(),
                                  Expanded(child: _buildListView())
                                ],
                              )))
                    ],
                  )
                ],
              ),
            )
          : SizedBox(
              height: 500,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Center(
                    child: Image.asset(
                      'images/ic_nojifen.png',
                      width: 175,
                      height: 122,
                    ),
                  ),
                ],
              ),
            ),
    );
  }

  /// 钱包信息
  Widget _buildHeadInfo() {
    return SliverToBoxAdapter(
        child: Container(
            margin: const EdgeInsets.only(bottom: 14),
            height: 137,
            alignment: Alignment.topLeft,
            child: Stack(
              children: [
                Image.asset(
                  'images/ic_point.png',
                  width: MediaQuery.of(context).size.width - 28,
                  fit: BoxFit.fill,
                ),
                Container(
                  margin: const EdgeInsets.only(left: 14, top: 30),
                  child: Text.rich(TextSpan(children: [
                    const TextSpan(
                        text: "我的积分\n\n",
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff5F3400),
                        )),
                    TextSpan(
                        text: ObjectUtil.isNotEmpty(_map['integralSum'])
                            ? _map['integralSum'].toString()
                            : "0",
                        style: const TextStyle(
                            color: Color(0xff5F3400),
                            fontSize: 41,
                            fontWeight: FontWeight.bold)),
                  ])),
                ),
              ],
            ) // ))
            ));
  }

  /// 筛选
  Widget _buildFilter() {
    return Container(
      height: 58,
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: GestureDetector(
        onTap: () {},
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              height: 30,
              decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5)),
                  color: const Color(0xFFF3F4F7)),
              alignment: Alignment.center,
              child: IconText(
                "2022年05月",
                style:
                    TextStyle(color: ThemeColor.pointTextColor, fontSize: 12),
                textAlign: TextAlign.end,
                icon: Icon(
                  Icons.arrow_drop_down,
                  color: ThemeColor.pointTextColor,
                  size: 12,
                ),
                beforeText: false,
              ),
            ),
            const Text.rich(TextSpan(children: [
              TextSpan(
                  text: "共 ",
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xffFFA100),
                  )),
              TextSpan(
                  text: "0.00",
                  style: TextStyle(
                      color: Color(0xff909090),
                      fontSize: 14,
                      fontWeight: FontWeight.bold)),
            ]))
          ],
        ),
      ),
    );
  }

  /// 列表
  Widget _buildListView() {
    return Container(
      color: Colors.white,
      child: ListView.builder(
        itemCount: _listData.length,
        itemBuilder: (ctx, index) {
          // return _buildItem();
          if (index == _listData.length) {
            //加载更多
            return _getMoreWidget();
          } else {
            if (_listData.isNotEmpty == true) {
              return _buildItem(_listData?[index]);
            } else {
              return Container();
            }
          }
        },
      ),
    );
  }

  /// 列表item
  Widget _buildItem(Map map) {
    return Container(
      height: 58,
      margin: const EdgeInsets.symmetric(horizontal: 12),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              bottom: BorderSide(width: 1, color: ThemeColor.dividerColor))),
      child: Row(
        children: [
          Expanded(
            child: Text.rich(TextSpan(children: [
              TextSpan(
                text: map['integralName'],
                style: TextStyle(color: ThemeColor.textColor, fontSize: 14),
              ),
              TextSpan(
                  text: "\r\n" +
                      map['addIntegralWeek'] +
                      ' ' +
                      map['addSpecificTime'],
                  style: TextStyle(
                      color: ThemeColor.textColorSecond, fontSize: 11))
            ])),
          ),
          Text(
            map['integralType'].toString() == 2
                ? ("-" + map['gainPoints'].toString())
                : ("+" + map['gainPoints'].toString()),
            style: TextStyle(
                color: ThemeColor.yellowColor,
                fontSize: 20,
                fontWeight: FontWeight.w600),
          )
        ],
      ),
    );
  }

  Widget _getMoreWidget() {
    return Center(
      child: Offstage(
        offstage: !isLoading,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: const <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }
}
